/**
 * Project: pws-formula
 * Created Date: Wednesday, May 2nd 2018, 10:44:22 am
 * Author: Thomas.Li
 * E-Mail: leeyinghui@hotmail.com
 * Intro: the helper of crc-modbus
 * -----
 * Last Modified: Wed May 02 2018
 * Modified By: Thomas.Li
 * -----
 * Copyright (c) 2018 pareact
 * ------------------------------------
 * Always bet on Javascript!
 */

const POLY = 0xA001;
const SEED = 0xFFFF;

function getCRC(buffer) {
  let crc = SEED;
  buffer.forEach(element => {
    crc = calcCRC(element, crc);
  });
  return crc;
}

function calcCRC(b, crc) {
  crc ^= b & 0xFF;
  for (let i = 0; i < 8; i++) {
    let carry = crc & 0x0001;
    crc >>= 1;
    if (carry) crc ^= POLY;
  }
  return crc;
}

module.exports = {
  getCRC: getCRC,
};

